package cn.bellychang.wangzheng.queue;

import cn.bellychang.bobo.queue.Queue;

/**
 * @author ChangLiang
 * @date 2021/1/28
 */
public class ArrayQueue<E> implements Queue<E> {

    private E[] items;

    /**
     * queue中元素个数
     */
    private int count;

    private int head = 0;

    /**
     * 下一个要插入的位置
     */
    private int tail = 0;

    /**
     * 数组大小
     */
    private int capacity;

    public ArrayQueue(int capacity) {
        items = (E[]) new Object[capacity];
        this.capacity = capacity;
    }

    @Override
    public int getSize() {
        return this.count;
    }

    @Override
    public boolean isEmpty() {
        return count == 0;
    }

    @Override
    public void enqueue(E e) {
        if (count == capacity) {
            throw new RuntimeException("queue is full");
        }
        items[tail++] = e;
        count++;
    }

    @Override
    public E dequeue() {
        if (count == 0) {
            throw new RuntimeException("queue is empty");
        }
        E temp = items[head];
        head++;
        count--;
        return temp;
    }

    @Override
    public E getFront() {
        if (count == 0) {
            throw new RuntimeException("queue is empty");
        }
        return items[head];
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Queue Tail {");
        for (int i = tail-1; i >= head; i--) {
            builder.append(items[i]).append("->");
        }
        return builder.toString().endsWith("->") ?
                builder.substring(0, builder.length() - 2) + "} Head" :
                builder.append("} Head").toString();
    }
}
